package cn.pconline.autoclub.web;

import cn.pconline.autoclub.entity.ClubPv;
import cn.pconline.autoclub.entity.MemberAll;
import cn.pconline.autoclub.entity.MemberWeek;
import cn.pconline.autoclub.service.ClubPvService;
import cn.pconline.autoclub.service.StatService;
import cn.pconline.autoclub.util.DateUtils;
import cn.pconline.autoclub.util.EncodeUtils;
import cn.pconline.autoclub.util.WebUtils;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import java.io.IOException;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.lang.StringUtils;
import org.gelivable.web.Env;
import org.gelivable.web.EnvUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * 提供统计相关的方法
 *
 * @author <a href="mailto:chensy0203@163.com">chensy</a>
 */
@Controller
@RequestMapping("/stat")
public class StatControler {

    @Autowired
    private StatService statService;
    @Autowired
    private ClubPvService clubPvService;
    private static final Logger log = LoggerFactory.getLogger(StatControler.class);

    private void printMsg(HttpServletResponse resp, String str, String callback) {
        callback = EncodeUtils.encodeForHTMLFilterNull(callback);
        try {
            java.io.PrintWriter w = resp.getWriter();
            if (StringUtils.isNotBlank(callback)) {
                w.print(callback + "(" + str + ")");
            } else {
                w.print(str);
            }
            w.flush();
            w.close();
        } catch (IOException ex) {
            log.error("response输出出错了", ex);
        }
    }

    /**
     * 获取用户的名次（全部排名）
     *
     * @param request
     * @param response
     * @throws IOException
     */
    @RequestMapping(value = "/getAllMemberRank", method = RequestMethod.GET)
    @ResponseBody
    public void getAllMemberRank(HttpServletRequest request, HttpServletResponse response) throws IOException {
        WebUtils.setEncoding(request, response);
        Env env = EnvUtils.getEnv();
        long clubId = env.paramLong("clubId");
        long userId = env.paramLong("userId");
        JSONObject obj = new JSONObject();
        MemberAll r = statService.getMemberAllByClubAndUser(clubId, userId);
        int rank = statService.getAllRank(clubId, userId);
        if (r == null || rank == -1) {
            obj.put("desc", "没有排名");
        } else {
            obj.put("petrol", r.getPetrol());
        }
        obj.put("rank", rank);
        printMsg(response, obj.toJSONString(), null);
    }

    /**
     * 获取用户的名称（周排名）
     *
     * @param request
     * @param response
     * @throws IOException
     */
    @RequestMapping(value = "/getWeekMemberRank", method = RequestMethod.GET)
    @ResponseBody
    public void getWeekMemberRank(HttpServletRequest request, HttpServletResponse response) throws IOException {
        WebUtils.setEncoding(request, response);
        Env env = EnvUtils.getEnv();
        long clubId = env.paramLong("clubId");
        long userId = env.paramLong("userId");
        JSONObject obj = new JSONObject();
        MemberWeek r = statService.getMemberWeekByClubAndUser(clubId, userId);
        int rank = statService.getWeekRank(clubId, userId);
        if (r == null || rank == -1) {
            obj.put("desc", "没有排名");
        } else {
            obj.put("petrol", r.getPetrol());
        }
        obj.put("rank", rank);
        printMsg(response, obj.toJSONString(), null);
    }

    @RequestMapping(value = "/getIndexPageView.do", method = RequestMethod.GET)
    @ResponseBody
    public void getIndexPageView(HttpServletRequest request, HttpServletResponse response) throws IOException {
        long clubId = WebUtils.paramLong(request, "clubId", 0);
        long total = clubPvService.countPvByClubId(clubId);
        long today = clubPvService.countPvByClubId(clubId, DateUtils.getTodayYmd());
        JSONObject obj = new JSONObject();
        obj.put("total", total);
        obj.put("today", today);
        printMsg(response, obj.toJSONString(), null);
    }

    @RequestMapping(value = "/getIndexLastPv.do", method = RequestMethod.GET)
    @ResponseBody
    public void getIndexLastPv(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String param = WebUtils.param(request, "param", "");
        String[] params = param.split(",");
        for (String p : params) {
            String[] t = p.split(":");
            if (t.length != 2) {
                continue;
            }
            String key = t[0];
            String value = t[1];
            request.setAttribute(key, value);
        }
        request.setCharacterEncoding("GBK");
        response.setContentType("text/html; charset=GBK");
        long clubId = WebUtils.paramLong(request, "clubId", 0);
        JSONArray arr = clubPvService.getClubPvsByDays(clubId, 7);
        JSONObject rs = new JSONObject();
        rs.put("history", arr);
        printMsg(response, rs.toJSONString(), null);
    }
}
